<template>
  <view class="hform-wrap">
    <h-toast></h-toast>
    <slot></slot>
  </view>
</template>
<script>
import HToast from "../hToast/index.vue";
import Taro from "@tarojs/taro";

export default {
  name: "hForm",
  components: {HToast},
  provide() {
    return {
      hForm: this
    };
  },
  props: {
    model: {
      type: Object,
      required: true,
      default() {
        return {}
      }
    },
    rules: {
      type: Object,
      default() {
        return {}
      }
    },
    labelWidth: {
      type: Number,
      default: 120
    }
  },
  data() {
    return {
      fields: [],
      initModelValue: ''
    }
  },
  created() {
    this.fields = []
    this.initModelValue = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    handleAddField(field) {
      if (field) this.fields.push(field);
    },
    resetFields() {
      this.fields.forEach(field => field.resetField())
    },
    validate(cb) {
      return new Promise(resolve => {
        let valid = true, count = 0;
        let errors = []
        this.fields.forEach(field => {
          field.validate('', error => {
            if (typeof error === 'string'){
              errors = errors.filter(data => data !== '')
              error && errors.push(error)
              valid = false;
            }
            if (++count === this.fields.length) {
              if(errors.length) {
                Taro.hToast({
                  message: errors[0]
                })
              }
              else if(!errors.length) {
                valid = true;
              }
              resolve(valid);
              if (typeof cb === 'function') cb(valid);
            }
          })
        })
      })
    }
  }
}
</script>

<style>
.hform-wrap {
  width: 100%;
  height: auto;
}
</style>
